import socket
import struct

charset = 'utf-8'

def tcp_client(message,server_host,server_port,secret):
    message = secret + message
    # 创建TCP客户端套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到服务器
    client_socket.connect((server_host, server_port))

    # 发送消息到服务器
    # 计算数据长度并将其转换为4字节的二进制表示
    message = message.encode(charset)
    data_length = len(message)
    length_header = struct.pack('!I', data_length)

    # 发送数据长度头部
    client_socket.send(length_header)

    # 发送数据
    client_socket.send(message)

    # 接收服务器的响应
    response_length_header = client_socket.recv(4)
    response_data_length = struct.unpack('!I', response_length_header)[0]
    received_data = b""
    while len(received_data) < response_data_length:
        remaining_bytes = response_data_length - len(received_data)
        chunk = client_socket.recv(remaining_bytes)
        if not chunk:
            raise Exception("无法接收足够的数据")
        received_data += chunk
    resp = received_data.decode(charset)
    # 关闭套接字
    client_socket.close()
    return resp